/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.ui;

import java.util.ArrayList;

import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.OrganizationData;
import edu.bsu.android.gtv.apps.bconnected.data.PersonData;
import edu.bsu.android.gtv.apps.bconnected.objects.Organization;
import edu.bsu.android.gtv.apps.bconnected.objects.Person;
import edu.bsu.android.gtv.apps.bconnected.ui.HomeActivity;
import edu.bsu.android.gtv.apps.bconnected.ui.base.BaseActivity;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;
import edu.bsu.android.gtv.apps.bconnected.util.Constants;
import edu.bsu.android.gtv.apps.bconnected.util.LoginHelper;
import edu.bsu.android.gtv.apps.bconnected.util.UIUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * An activity that shows detail information for an organization, including description, members and contact info. Activity that is started when a 
 * user selects an organization from the list on the {@link OrganizationFragment}.
 * @author Kyle Parker, University Computing Services
 */
public class OrganizationInfoActivity extends BaseActivity {
    private static final String TAG = "OrganizationInfoActivity";
    private static final String TAG_CONTACT = "contact";
    private static final String TAG_DESCRIPTION = "desc";
    private static final String TAG_MEMBERS = "members";

    private TabHost mTabHost;
    private View mLoadingSpinner;
    private View mMemberSpinner;
    private Activity mActivity;
    private Organization mOrganization;
    private BroadcastReceiver mReceiver;

    private String mLoginGuid;
    private String mBSUID;
    private String mName;
    private String mUrl;
    private String mOrganizationID = "";
    private boolean mLogin;

    private int mOrganizationPosition = 0; 
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_organization_info);
		
        getActivityHelper().setupActionBar(false, "Student Orgs | Organization Info");        
        mActivity = this;
        
        handleLogout();    
        handleLogin();
                
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
       	mTabHost.setup();

        mLoadingSpinner = findViewById(R.id.loading_spinner); 
        mLoadingSpinner.setVisibility(View.VISIBLE);	
        
        mMemberSpinner = findViewById(R.id.spinner_members); 
        mMemberSpinner.setVisibility(View.VISIBLE);

        setupDescriptionTab();
        setupMembersTab();
        setupContactInfoTab();

        getExtras();
		// Hide the organization information while the data is loading
		hideOrganizationInfo();
		if (mLogin) {
			loadOrganizationInfo();
		}

		// Set the current tab to the last selection of the student - either the description or the members
        mTabHost.setCurrentTab(UIUtils.getLastID(mActivity, Constants.PREF_ORGANIZATION_TAB));
        // Reset the tab position
        UIUtils.setLastID(mActivity, Constants.PREF_ORGANIZATION_TAB, 0);

        AnalyticsUtils.getInstance(mActivity).trackPageView("/OrganizationInfo");
    }
    
    @Override 
    public void onDestroy() {
    	super.onResume();
    	mActivity.unregisterReceiver(mReceiver);
    }
    
    /**
     * Get the extras from the Intent
     */
    public void getExtras() {
		Bundle extras = getIntent().getExtras();  
 
		if (extras != null) {
			if (extras.getString(Constants.EXTRA_ORGANIZATION_POSITION) != null) {
				mOrganizationPosition = Integer.parseInt(extras.getString(Constants.EXTRA_ORGANIZATION_POSITION));
			}
			if (extras.getString(Constants.EXTRA_ORGANIZATION_ID) != null) {
				mOrganizationID = extras.getString(Constants.EXTRA_ORGANIZATION_ID);
			}
		}
    }

    /**
     * Using a new thread, separate from the main activity, load the organization information from the service handler
     */
    public void loadOrganizationInfo() {	
        Runnable load = new Runnable(){
            public void run() {
            	try {
	    	        if (OrganizationData.getOrganizationCount() > 0) {
	    	        	// The organization ID may already be set if the user is returning from the member information
	    	        	if (mOrganizationID.length() == 0) {
		    	        	Organization org = OrganizationData.getOrganization(mOrganizationPosition);
		    	        	
		    	        	mOrganizationID = org.getOrganizationID();
	    	        	}
	    	        	
	    	        	OrganizationData.initializeOrganization(mOrganizationID, mActivity);
		    	        
		                if (OrganizationData.getOrganizationCount() > 0) {
		                	mOrganization = OrganizationData.getOrganization();
		                }
            		}
	    	        
	    	    	mActivity.runOnUiThread(returnOrganization);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}    	    	
            }
        };
        
        Thread thread = new Thread(null, load, "loadOrganizationInfo");
        thread.start();
    }
    
    /**
     * Load the organization info from the service handler and set the visibility of the spinner to "gone"
     */
    private Runnable returnOrganization = new Runnable(){
        public void run() {
            displayOrganizationInfo();
            mLoadingSpinner.setVisibility(View.GONE);
        }
    };

    /**
     * Using a new thread, separate from the main activity, load the members from the service handler
     */
    private void loadMember() {		 
        Runnable load = new Runnable(){
            public void run() {
            	try {            		
    	        	PersonData.initializeMember(mOrganization.getOrganizationID(), mBSUID, mLoginGuid, mActivity);  
	    	    	
	    	    	mActivity.runOnUiThread(returnMember);  
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread = new Thread(null, load, "loadMember");
        thread.start();
    }
    
    /**
     * Load the members from the service handler
     */
    private Runnable returnMember = new Runnable(){
        public void run() {
        	// If the call to the member service did not return the "error" attribute, then display the member information, otherwise 
        	// the expiration date has expired for the user or they are not authorized under the current credentials to access the information.
        	// When retrieving data from the .NET service handler, the BSU ID and login guid are matched against the SQL Server database.  If
        	// the combination of the two do not match, then the user is not permitted to retrieve the requested data.  The guards against
        	// someone hacking the querystring parameters to retrieve the information of another student.
        	if (PersonData.getMemberAuth()) {
        		displayMembers();

                if (PersonData.getMemberCount() == 0) {
                    TextView empty = ((TextView) findViewById(R.id.empty_members)); 
                    empty.setVisibility(View.VISIBLE);
                }
        	} else {
                findViewById(R.id.organization_info_container).setVisibility(View.VISIBLE);
                TextView empty = ((TextView) findViewById(R.id.empty_members));
                empty.setVisibility(View.VISIBLE);
                empty.setText(R.string.error_auth);
        	}
        	
        	mMemberSpinner.setVisibility(View.GONE);
        }
    };
    
    /**
     * Display the organization information and members
     */
    private void displayOrganizationInfo() {
    	if (mOrganization != null) {
    		LinearLayout view = (LinearLayout) findViewById(R.id.organization_info_container);
	        view.setVisibility(View.VISIBLE);
        	view.setBackgroundResource(R.color.content_background);
            
            loadMember();
            
        	mUrl = mOrganization.getShareURL().toString();
        	mName = mOrganization.getOrganizationName();
        	
        	UIUtils.displayTextView(view, R.id.organization_name, mOrganization.getOrganizationName());
        	UIUtils.displayTextView(view, R.id.category, mOrganization.getCategory());
        	UIUtils.displayTextView(view, R.id.organization_desc, mOrganization.getOrganizationDesc());
        	if (mOrganization.getMembershipReq().length() > 0) {
        		UIUtils.displayTextView(view, R.id.requirements, mOrganization.getMembershipReq());
        	}
        	if (mOrganization.getFounded().length() > 0) {
        		view.findViewById(R.id.empty_contact_info).setVisibility(View.GONE);
                view.findViewById(R.id.founded).setVisibility(View.VISIBLE);
                UIUtils.displayTextView(view, R.id.founded, mActivity.getString(R.string.content_founded) + " " + mOrganization.getFounded());
        	}
        	if (mOrganization.getAddress().length() > 0) {
        		view.findViewById(R.id.empty_contact_info).setVisibility(View.GONE);
        		view.findViewById(R.id.address).setVisibility(View.VISIBLE);
                UIUtils.displayTextView(view, R.id.address, mOrganization.getAddress());
        	}
        	if (mOrganization.getEmailAddress().length() > 0) {
        		view.findViewById(R.id.empty_contact_info).setVisibility(View.GONE);
        		view.findViewById(R.id.email).setVisibility(View.VISIBLE);
                UIUtils.displayTextView(view, R.id.email, mOrganization.getEmailAddress());
        	}
        	if (mOrganization.getPhone().length() > 0) {
        		view.findViewById(R.id.empty_contact_info).setVisibility(View.GONE);
        		view.findViewById(R.id.phone).setVisibility(View.VISIBLE);
                UIUtils.displayTextView(view, R.id.phone, mOrganization.getPhone());
        	}
        	if (mOrganization.getWebsite().length() > 0) {
        		view.findViewById(R.id.empty_contact_info).setVisibility(View.GONE);
        		view.findViewById(R.id.website).setVisibility(View.VISIBLE);
                UIUtils.displayTextView(view, R.id.website, mOrganization.getWebsite());
        	}      	
    	} else {
    		hideOrganizationInfo();
    	}
    }

    /**
     * Hide the organization view during the load process or if the organization object is empty
     */
    private void hideOrganizationInfo() { 
    	LinearLayout view = (LinearLayout) findViewById(R.id.organization_info_container);
        view.setVisibility(View.GONE);			
        view.setBackgroundResource(R.drawable.empty_people_background);
    }
    
    /**
     * Display the members for the organization
     */
    private void displayMembers() {   
    	if (PersonData.getMemberCount() > 0) {
            MemberAdapter adapter = new MemberAdapter(mActivity, PersonData.getMembers());

            final ListView lv = ((ListView) findViewById(R.id.members));
            lv.setAdapter(adapter); 
            lv.setOnItemClickListener(new OnItemClickListener(){ 
    			public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) {
    		        final Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, MemberInfoActivity.class);

    		        // In order to get the correct member on the member info activity, get the BSU ID, member type and member role at the position specified 
    		        // and return as an extra in the intent
    		        Person member = (Person) lv.getItemAtPosition(position);
    		        
    		        intent.putExtra(Constants.EXTRA_BSU_ID, member.getBSUID());
    		        intent.putExtra(Constants.EXTRA_PERSON_TYPE_ID, member.getMemberTypeID());
    		        intent.putExtra(Constants.EXTRA_MEMBER_ROLE, member.getMemberRole());
    		        intent.putExtra(Constants.EXTRA_MEMBER_POSITION, Integer.toString(position));
    		        intent.putExtra(Constants.EXTRA_ORGANIZATION_POSITION, Integer.toString(mOrganizationPosition));

    		        UIUtils.setLastID(mActivity, Constants.PREF_ORGANIZATION_TAB, 1); 
    		        
    		        mActivity.startActivity(intent);
    			}
    		});
    	}
    }

    /**
     * MemberAdapter used to populate the listview for the members
     */
    private class MemberAdapter extends ArrayAdapter<Person> {
        private ArrayList<Person> items;
        
        public MemberAdapter(Context context, ArrayList<Person> items) {
            super(context, 0, items);
            this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent)  {              	
            View view = convertView;
            
            if (view == null) {
            	view = LayoutInflater.from(mActivity).inflate(R.layout.list_item_twoline, null);
            }
            
            // Retrieve the member information and set the TextView items for the list
            Person member = items.get(position);  
            
            if (member != null) {          		
            	UIUtils.displayTextView(view, R.id.title, (member.getLastName() + ", " + member.getFirstName() + " " + 
            			member.getNameSuffix()).trim()); 

            	if (Integer.parseInt(member.getMemberTypeID()) != Constants.VALUE_PERSON_TYPE_STUDENT) {
                	UIUtils.displayTextView(view, R.id.desc, member.getMemberRole());
            	} else {
                	((TextView) view.findViewById(R.id.desc)).setVisibility(View.GONE);
            	}
            }
             
            return view;
        }
    }
    
    /**
     * Build and add "description" tab.
     */
    private void setupDescriptionTab() {
        mTabHost.addTab(mTabHost.newTabSpec(TAG_DESCRIPTION)
                .setIndicator(UIUtils.buildIndicator(R.string.tab_description, mActivity))
                .setContent(R.id.tab_organization_desc));
    }
    
    /**
     * Build and add "member" tab.
     */
    private void setupMembersTab() {
        mTabHost.addTab(mTabHost.newTabSpec(TAG_MEMBERS)
                .setIndicator(UIUtils.buildIndicator(R.string.tab_organization_members, mActivity))
                .setContent(R.id.tab_member));
    }
    
    /**
     * Build and add "contact info" tab.
     */
    private void setupContactInfoTab() {
        mTabHost.addTab(mTabHost.newTabSpec(TAG_CONTACT)
                .setIndicator(UIUtils.buildIndicator(R.string.tab_contact_info, mActivity))
                .setContent(R.id.tab_contact_info));
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = new MenuInflater(this);
    	inflater.inflate(R.menu.share_menu_items, menu);
    	
    	super.onCreateOptionsMenu(menu);
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        final String shareString;
        final Intent intent;

        switch (item.getItemId()) {
            case R.id.menu_share:
                shareString = mActivity.getString(R.string.content_organization_share) + " " + mName + " at " + mUrl;
                intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, mName);
                intent.putExtra(Intent.EXTRA_TEXT, shareString);
                startActivity(Intent.createChooser(intent, getText(R.string.title_share)));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /** 
     * In order to protect the activity from the back stack after a student logs out, remove the activity 
     * If the student hits the back button, this will take them to the Home activity
     */
    private void handleLogout() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_LOGOUT);
        mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
		        intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
		        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_LOGOUT));
		        
		        mActivity.startActivity(intent); 
			    mActivity.finish();
			}
		};
		
        mActivity.registerReceiver(mReceiver, intentFilter);
    }
    
    /**
     * Determine if the person has logged in and whether there is a person object in the database
     * Get the student's BSU ID for use throughout the application
     */
    private void handleLogin() {
    	Person person = LoginHelper.checkLogin(mActivity);
    	
    	if (person != null) {
    		mBSUID = person.getBSUID();
        	mLoginGuid = person.getLoginGuid();
        	mLogin = true;
    	} else {
	        Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
	        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_NOT_LOGGED_IN));
	        
	        mActivity.startActivity(intent); 
		    mActivity.finish();
		    
		    mLogin = false;
    	}    	
    }
}
